package controller.common;

import controller.entity.Excel;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import service.GoodsService;
import service.UserService;
import utils.ExcelUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Created by asus on 2017/6/20.
 */
@Controller

public class ExcelController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserService userService;

    private List getAllGoods() {
        return goodsService.getAllGoods();
    }


    @RequestMapping("/excel")
    public void Test(Excel excel, HttpServletResponse response) {
        System.out.println(excel);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + excel.getMethodName() + ".xls");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            //创建工作博
            WritableWorkbook writableWorkbook = Workbook.createWorkbook(out);
            //创建sheet
            WritableSheet sheet = writableWorkbook.createSheet("sheet1", 0);
            Method method = this.getClass().getDeclaredMethod(excel.getMethodName());
            method.setAccessible(true);// 调用private方法的关键一句话
            List list = (List) method.invoke(this);
            System.out.println(list);
            ExcelUtils.outputHeaders(excel.getTitles().split(","), sheet);
            ExcelUtils.outputColumns(excel.getFields().split(","), list, sheet, 1);
            //获取输出流，写入excel 并关闭
            writableWorkbook.write();
            writableWorkbook.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
